<template>
  <div class="applicationDetail">
    <div class="title-box"><span>弹性伸缩管理</span><span class="back return" @click="goback">&lt;&nbsp;返回</span></div>
    <div class="details">
      <div class="title">弹性伸缩详情</div>
      <div class="dialog-content">
        <div class="warp">
          <div v-for="(item1, key1) in contentInfo" :key="key1" class="warp">
            <div class="data-box" v-for="(item, key) in item1" :key="key">
              <template v-if="key !== 'target_based_configuration' && key !== 'name'">
                <div class="label">
                  <span>{{ dictionary[key] ? dictionary[key] : key }}</span>
                </div>
                <div class="name-value hae-input">{{ $t(item) }}</div>
              </template>
              <template v-else-if="key === 'name'">
                <div class="label">
                  <span>{{ dictionary[key] ? dictionary[key] : key }}</span>
                </div>
                <div class="name-value hae-input" v-if="!showEdit[key]">{{ $t(item) }}</div>
                <div class="content-text" v-else>
                  <el-input v-model.trim="basicData.data[key]" maxlength="1024" />
                </div>
                <div class="edit">
                  <div v-if="!showEdit[key]" class="actions-box">
                    <div class="actions-details heigt-l" @click="changeUser(key)">修改</div>
                  </div>
                  <div v-else class="actions-box">
                    <div class="actions-details" @click="onSubmit(key)">保存</div>
                    <div class="line"></div>
                    <div class="actions-details" @click="closeRow(key, false)">取消</div>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="lv2-box" v-for="(p, k) in item" :key="k">
                  <div class="label">
                    <span>{{ dictionary[key][k] ? dictionary[key][k] : k }}</span>
                  </div>
                  <div class="name-value hae-input" v-if="!showEdit[k]">{{ $t(p) }}</div>
                  <div class="content-text" v-else>
                    <el-input v-model.number="basicData.data[key][k]" v-if="`${k}` != 'metric_name'" />
                    <el-select v-model="basicData.data[key][k]" v-else placeholder="请选择指标名称" size="large">
                      <el-option v-for="item in metric_name_options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </div>
                  <div class="edit">
                    <div v-if="!showEdit[k]" class="actions-box">
                      <div class="actions-details heigt-l" @click="changeUser(`${k}`)" v-if="userType >= 5">修改</div>
                    </div>
                    <div v-else class="actions-box">
                      <div class="actions-details" @click="onSubmit(`${k}`)">保存</div>
                      <div class="line"></div>
                      <div class="actions-details" @click="closeRow(`${k}`, false)">取消</div>
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
      <div id="aliasManager">
        <div class="insert-top">
          <div class="titles">关联Fleet</div>
          <el-button class="btn" @click="dialogVisibtn()">新增关联</el-button>
        </div>
        <div class="table-box">
          <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#f4f5f8', color: '#252b3a' }" :border="true">
            <el-table-column label="Fleet名称/ID" class-name="elcell" width="260">
              <template #default="scope">
                <div class="toDetails" @click="toDetails(scope.row.fleet_id, scope.row.name)">
                  {{ scope.row.name }}
                </div>
                <el-tooltip effect="dark" :content="scope.row.fleet_id" placement="bottom">
                  <div class="id-box">
                    {{ scope.row.fleet_id }}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="state" label="状态">
              <template #default="scope">
                {{ scope.row.state ? $t('alias.' + scope.row.state) : '' }}
              </template>
            </el-table-column>
            <el-table-column prop="instance_count" label="实例数量"> </el-table-column>
            <el-table-column prop="process_count" label="进程数量" />
            <el-table-column prop="server_session_count" label="会话数量" />
            <el-table-column prop="max_server_session_count" label="最大会话数量" />
            <el-table-column fixed="right" label="操作" width="180" v-if="userType >= 5">
              <template #default="scope">
                <div v-if="!scope.row.isEdit" class="actions-box">
                  <div class="actions-details" @click="deleteScaling(scope.row.fleet_id, scope.row.name)">解绑</div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 新增关联弹框 -->
        <el-dialog title="新增关联Fleet" v-model="dialogVisible" width="500px" center>
          <el-form ref="assRef" :model="formModel">
            <el-form-item prop="fleet_id">
              <template #label>
                <div class="item-label">Fleet ID</div>
                <el-tooltip effect="dark" placement="right" content="应用进程队列的id"
                  ><el-icon><QuestionFilled /></el-icon
                ></el-tooltip>
              </template>
              <el-select v-model="aliasValue" class="m-2 fleet" placeholder="请选择fleet" @change="changeFleet">
                <el-option v-for="item in fleetOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
                  <div class="fleetLabel">{{ item.label }}</div>
                  <div class="fleetValue">{{ item.value }}</div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="reviseDataset(assRef)">创建</el-button>
              </span>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ElMessage, ElMessageBox, FormRules, FormInstance } from 'element-plus'
  import router from '@/router'
  import appStore from '@/store'
  import { useRoute } from 'vue-router'
  import { reactive, ref, onUnmounted } from 'vue'
  import autoScaling from '@/api/autoScaling'
  import FleetsService from '@/api/fleetsService'
  import { useI18n } from 'vue-i18n'
  const { t } = useI18n()
  const route = useRoute()
  const emit = defineEmits(['close'])
  const dialogVisible = ref(false)
  const assRef = ref<FormInstance>()
  const disabled = ref(false)
  const metric_name_options = [
    {
      value: 'PERCENT_AVAILABLE_SERVER_SESSIONS',
      label: t('PERCENT_AVAILABLE_SERVER_SESSIONS')
    }
  ]

  const dictionary: { [key: string]: string | { [key: string | number]: string } } = {
    policy_id: '弹性伸缩ID',
    policy_type: '策略类型',
    scaling_target: '伸缩目标',
    name: '名称',
    state: '状态',
    target_based_configuration: {
      metric_name: '指标名称',
      max_target_value: '最大目标可用会话比',
      min_target_value: '最小目标可用会话比'
    }
  }
  let userType = ref()
  userType.value = localStorage.getItem('UserType') as string
  let contentInfo = reactive([]) as Array<{ [key: string]: string | any }>
  let basicData: { [key: string]: { [key: string]: string | any | { [key: string | number]: string } } } = reactive({ data: {} })
  let showEdit = ref({
    name: false,
    metric_name: false,
    max_target_value: false,
    min_target_value: false
  } as { [key: string]: boolean })
  const changeUser = (key: string) => {
    for (const k in showEdit.value) {
      if (k != key) {
        showEdit.value[k] = false
      }
    }
    contentInfo.forEach((item) => {
      basicData.data = {
        name: item ? item.name : '',
        target_based_configuration: {
          metric_name: item ? item.target_based_configuration.metric_name : '',
          min_target_value: item ? item.target_based_configuration.min_target_value : '',
          max_target_value: item ? item.target_based_configuration.max_target_value : ''
        }
      }
    })
    showEdit.value[key] = true
  }
  const closeRow = async (key: string, change: boolean) => {
    showEdit.value[key] = false
    showEdit.value.max_target_value = false
    showEdit.value.min_target_value = false
    if (change) {
      emit('close', true)
    }
  }
  let aliasValue = ref('')
  const goback = () => {
    router.push({ name: 'autoScaling' })
  }
  const param = reactive({
    project_id: appStore.userStore.project_id,
    policy_id: `${route.params.id}`,
    offset: 1,
    limit: 10,
    fleet_id: ''
  })
  const dataList = reactive({
    project_id: appStore.userStore.project_id,
    policy_id: '',
    offset: 1,
    limit: 10,
    name: '',
    fleet_id: '',
    state: '',
    intance_count: 0,
    process_count: 0,
    server_session_count: 0,
    max_server_session_count: 0
  })
  const submit = async (param: any, key: string) => {
    try {
      let res = await autoScaling.changeAutoScaling(param)
      if (res.status < 300) {
        ElMessage({
          message: '修改成功',
          type: 'success'
        })
        closeRow(key, true)
        getDetails()
      }
    } catch (err) {
      ElMessage.error('修改失败')
    }
  }
  const onSubmit = async (key: string) => {
    let param = {
      autoScaling: {
        name: '',
        target_based_configuration: {
          metric_name: '',
          min_target_value: 1,
          max_target_value: 100
        }
      },
      policy_id: ''
    }
    param.policy_id = contentInfo ? `${route.params.id}` : ''
    param.autoScaling = JSON.parse(JSON.stringify(basicData.data))

    if (!param.autoScaling.name) {
      ElMessageBox.confirm('请输弹性伸缩名称', '警告', {
        type: 'warning'
      })
      return false
    }
    if (!param.autoScaling.target_based_configuration.metric_name) {
      ElMessageBox.confirm('请选择指标名称', '警告', {
        type: 'warning'
      })
      return false
    }
    if (!param.autoScaling.target_based_configuration.min_target_value) {
      ElMessageBox.confirm('请输入大于0的最小目标可用会话比', '警告', {
        confirmButtonText: 'OK',
        type: 'warning'
      })
      return false
    } else if (!param.autoScaling.target_based_configuration.max_target_value) {
      ElMessageBox.confirm('请输入大于0的最大目标可用会话比', '警告', {
        type: 'warning'
      })
      return false
    }
    if (
      key === 'min_target_value' &&
      param.autoScaling.target_based_configuration.max_target_value < param.autoScaling.target_based_configuration.min_target_value
    ) {
      ElMessageBox.alert('最小目标可用会话比应小于等于最大目标可用会话比', '警告', {
        type: 'warning'
      })
      return false
    } else if (
      key === 'max_target_value' &&
      param.autoScaling.target_based_configuration.min_target_value > param.autoScaling.target_based_configuration.max_target_value
    ) {
      ElMessageBox.alert('最大目标可用会话比应大于等于最小目标可用会话比', '警告', {
        type: 'warning'
      })
      return false
    }
    submit(param, key)
  }
  const toDetails = (id: string, name: string) => {
    router.push({ name: 'fleetDetails', params: { id, name } })
  }
  interface optionList {
    value: string
    label: string
    disabled: boolean
  }
  let tableData: optionList[] = reactive([])
  let fleetOptions: optionList[] = reactive([])
  const changeFleet = (fleet: string) => {
    param.fleet_id = fleet
  }
  const getFleets = async () => {
    let res = await autoScaling.getFleetList(param)
    let storage: optionList[] = reactive([])
    if (res.status == 200 && res.data.fleets) {
      res.data.fleets.forEach((item: any) => {
        if (item.state === 'ACTIVE') {
          const itemJson = tableData.find((task: any) => item.fleet_id === task.fleet_id)
          storage.push({
            label: `${item.name}`,
            value: item.fleet_id,
            disabled: itemJson ? true : false
          })
        }
      })
    }
    fleetOptions = storage
  }
  const getAutoScalingFleet = async () => {
    param.policy_id = `${route.params.id}`
    let res = await autoScaling.getAutoScalingFleet(param)
    tableData.length = 0
    tableData.push(...res.data.associated_fleet_of_policy_list)
    getFleets()
  }
  const deleteScaling = (fleet_id: any, name: any) => {
    ElMessageBox.confirm(`确认解绑此条数据？\n名称: ${name}\nID: ${fleet_id} `, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        param.policy_id = `${route.params.id}`
        param.fleet_id = fleet_id
        let res = await autoScaling.deleteAutoFleet(param)
        if (res.status === 204) {
          ElMessage({
            type: 'success',
            message: '解绑成功'
          })
          getAutoScalingFleet()
        } else {
          ElMessage({
            type: 'info',
            message: '解绑失败'
          })
        }
      })
      .catch(() => {})
  }
  const bodyClose = (e: any) => {
    if (e.target.className === 'dialog') {
      emit('close')
    }
  }
  document.addEventListener('click', bodyClose)
  onUnmounted(() => {
    document.removeEventListener('click', bodyClose)
  })

  const dialogVisibtn = async () => {
    aliasValue.value = ''
    dialogVisible.value = true
  }
  const formModel = reactive<{
    fleet_id: ''
  }>({
    fleet_id: ''
  })

  // 创建
  const reviseDataset = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        dataList.fleet_id = aliasValue.value
        dataList.policy_id = `${route.params.id}`
        if (aliasValue.value.length > 0) {
          try {
            let res = await autoScaling.toBindAutoScaling(dataList)
            if (res.status < 300) {
              ElMessage({
                message: '创建成功',
                type: 'success'
              })
              getAutoScalingFleet()
              dialogVisible.value = false
            }
          } catch (err) {
            ElMessage.error('创建失败')
          }
        }
      }
    })
  }

  const getDetails = async () => {
    param.policy_id = `${route.params.id}`
    let res = await autoScaling.getDetails(param)
    if (res.status == 200) {
      contentInfo.length = 0
      contentInfo.push(res.data)
    }
  }

  getAutoScalingFleet()
  getDetails()
</script>
<style>
  .el-input__wrapper {
    height: 30px;
  }
</style>
<style lang="scss" scoped>
  @import '@/assets/scss/dropdownBox.scss';
  :deep(.el-select) {
    width: 220px;
  }
  .applicationDetail {
    .title-box {
      span {
        font-size: 16px;
        font-weight: bold;
        margin-left: 20px;
        margin-right: 21px;
        line-height: 60px;
      }
      .return {
        margin-left: -12px;
        color: #325cb0;
        font-size: 14px;
        cursor: pointer;
      }
    }
    .heigt-l {
      color: $main-color;
      min-width: 200px;
      font-size: 14px;
    }
    .actions-details {
      font-size: 14px;
    }
    .warp {
      display: flex;
      flex-wrap: wrap;
    }

    .data-box {
      display: flex;
      width: 33%;
      margin-bottom: 24px;
      align-items: center;

      .label {
        display: inline-block;
        flex-shrink: 0;
        font-size: 14px;
        color: $action-color;
        line-height: 30px;
        height: 30px;
        margin-right: 20px;
        text-align: left;
        white-space: nowrap;

        span {
          display: inline-block;
          width: 130px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .name-value {
        width: auto;
        margin-right: 30px;
        height: 30px;
        line-height: 30px;
        color: $text-color;
        font-size: 14px;
      }
      .content-text {
        margin-right: 30px;
      }
    }
    .data-box:last-child {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      .lv2-box {
        display: flex;
        width: 33%;
        margin-bottom: 24px;
        align-items: center;
      }
    }
    #aliasManager {
      background-color: $blank-color;
      padding: 0;
      .insert-top {
        padding-bottom: 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .titles {
          font-size: 14px;
          font-weight: bold;
          color: #252b3a;
          margin-bottom: 0;
        }
        .btn {
          width: 100px;
          height: 30px;
        }
      }
      .el-dialog .el-form-item {
        flex-direction: column;
        align-items: flex-start;
      }
      .el-select {
        width: 400px;
      }
      .dialog-footer button:first-child {
        margin-right: 10px;
      }
      :deep(.el-input__wrapper) {
        width: 380px;
      }
      .dialog-enter-active {
        transition: all 0.3s ease;
      }

      .dialog-leave-active {
        transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
      }

      .dialog-enter,
      .dialog-leave-to {
        transform: translateX(10px);
        opacity: 0;
      }
      :deep(.el-input) {
        height: 28px;
        line-height: 28px;
        .el-input__wrapper {
          border-radius: 2px;
        }
        .el-input__inner {
          height: 28px;
          line-height: 28px;
        }
      }

      .search-box {
        display: flex;
        margin: 20px 0;
        align-items: center;
        .run-select {
          width: 160px;
          margin-right: 20px;
        }
      }
      .table-box {
        border-radius: 2px;
      }
      .demo-pagination-block {
        margin-top: 20px;
        position: relative;
        .el-pagination {
          justify-content: flex-end;
        }
        :deep(.el-pagination__total) {
          position: absolute;
          left: 0;
        }
        :deep(.el-pagination__sizes) {
          position: absolute;
          left: 58px;
        }
        :deep(.btn-next) {
          min-width: 28px;
          height: 28px;
          background: $blank-color;
          border: 1px solid $border-color;
          color: $text-color;
        }
        :deep(.btn-next:hover) {
          background: $bac-color;
        }
        :deep(.btn-prev) {
          min-width: 28px;
          height: 28px;
          background: $blank-color;
          border: 1px solid $border-color;
          color: $text-color;
        }
        :deep(.btn-prev:hover) {
          background: $bac-color;
        }
        :deep(.el-pager) {
          li {
            padding: 0;
            min-width: 28px;
          }
          .number,
          .more {
            height: 28px;
            background: $blank-color;
            border: 1px solid $border-color;
            color: $text-color;
          }
          .number:hover,
          .more:hover {
            background: $bac-color;
          }
          .is-active {
            border-color: $main-color;
            color: $main-color;
            background: $bac-color;
            font-weight: normal;
          }
        }
      }
      :deep(.id-box) {
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .change {
        width: 170px;
      }
      .el-icon {
        margin-left: 10px;
        margin-top: -4px;
        color: #b4b6be;
      }
      :deep(.el-form-item__label) {
        display: inline-flex;
        align-items: center;
      }
      :deep(.el-table) {
        border-radius: 2px;
        font-size: 14px;
        color: $text-color;
        tr {
          border-color: $border-color;
          height: 78px;
        }
        thead > tr:first-child {
          height: 36px;
        }
        .el-table__cell {
          border-right: none;
        }
      }
      :deep(.toDetails) {
        color: $main-color;
        cursor: pointer;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      :deep(.toDetails:hover) {
        text-decoration: underline;
      }
      :deep(.id-box) {
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      :deep(.cell) {
        padding: 0 30px 0 20px;
      }
    }
  }
</style>
